package com.android.sq.zouqi.event;

import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.android.sq.zouqi.Constants;
import com.android.sq.zouqi.user.pTableUserInfo;
import com.android.sq.zouqi.util.ServerData;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class pCtrlEventInfo {
	private final static String TAG ="pCtrlEventInfo";
	private Context context;
	private Handler handler;
	private SharedPreferences share;
	private ServerData server_data = null;
	private final String url_get_event_info 	= "/zouqi/EventManage/pGetEventInfo.php";
	private final String url_save_event_info 	= "/zouqi/EventManage/pSaveEventInfo.php";
	private final String url_send_invitation 	= "/zouqi/EventManage/pSendInvitation.php";
	private final String url_state_change 		= "/zouqi/EventManage/pEventStateChange.php";
	private final String url_get_event_list 	= "/zouqi/EventManage/pGetEventList.php";
	private final String url_confirm_invitation = "/zouqi/EventManage/pConfirmInvitation.php";
	private final String url_unconfirmed_event 	= "/zouqi/EventManage/pGetEventUnconfirmed.php";
	private final String url_event_users		= "/zouqi/EventManage/pGetUserEvents.php";	
	private final String url_save_location_info = "/zouqi/EventManage/pSaveLocationInfo.php";
	private String error_msg = "";
	public pCtrlEventInfo(Context context, Handler handler) {
		this.context = context;
		this.handler = handler;
		share = context.getSharedPreferences(Constants.SP_USER_INFO, Context.MODE_PRIVATE);
	}
	
	public void handleErrorMsg(String error_msg) {
		this.error_msg = error_msg;
		Message msg = new Message();
		Bundle data = msg.getData();
		data.putString("ERROR", this.error_msg);
		handler.sendMessage(msg);
	}
	
	// 获取活动信息数据 - pCC02F01
	// 根据给定的活动id获得活动信息的数据
	public pTableEventInfo pGetEventInfo(int event_id) {
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_ID, "" + event_id));
		server_data = new ServerData(Constants.SERVER_URL + url_get_event_info, params);
		pTableEventInfo event = getEvent(server_data.getResultJsonString());
		/*if (event == null) {
			Log.e("BA", "pCtrlEventInfo->pGetEventInfo: event is null");
		} else {
			Log.e("BA", "---------------pCtrlEventInfo->pGetEventInfo--------------");
			Log.e("BA", "_id = " + event.get_id());
			Log.e("BA", "states = " + event.getpEventState());
			Log.e("BA", "start_time = " + event.getpEventStart());
			Log.e("BA", "duration = " + event.getpEventDuration());
			Log.e("BA", "location_id = " + event.getpEventLocationId());
			Log.e("BA", "owner_id = " + event.getpEventOwnerId());
			Log.e("BA", "---------------pCtrlEventInfo->pGetEventInfo--------------");
		}*/
		return event;
	}
	
	/* 保存活动信息 - pCC02F02
	 * 向数据库中保存给出的活动实例 ；如果给出的活动实例中活动id为空值则是新建活动，否则是修改活动信息。
	 * 如果是新建活动，还需要向pTableUserEvent中插入一条记录，
	 * pIfConfirmInvite值为0，表示活动为该用户创建
	 * 如果操作成功则返回该活动的活动id，否则返回空值。
	 * return_id = -1 	操作失败
	 * return_id = 0  	未更新
	 * return_id = n	返回的id
	 */
	public int pSaveEventInfo(pTableEventInfo event) {
		int return_id = -1;
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_ID, "" + event.get_id()));
		if (event.get_id() == -1) { //新建活动
			params.add(new BasicNameValuePair(Constants.PARAM_EVENT_STATE, "" + Constants.EVENT_STATE_UNSTARTED));
		} else {
			params.add(new BasicNameValuePair(Constants.PARAM_EVENT_STATE, "" + event.getpEventState()));
		}
		// 需要将'yyyy-mm-dd hh:mm:ss'格式的时间转换成毫秒数，传给服务器
		long start_ms = dateToMSecond(event.getpEventStart());
		long durat_ms = dateToMSecond(event.getpEventDuration());
		Log.e(TAG, "开始时间毫秒数=" + start_ms);
		Log.e(TAG, "结束时间毫秒数=" + durat_ms);
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_START, "" + start_ms));
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_DURATION, "" + durat_ms));
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_BYNAME, "" + event.getpEventByname()));
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_LATITUDE, "" + event.getpEventLatitude()));
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_LONGITUDE, "" + event.getpEventLongitude()));
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_ADDRESS, "" + event.getpEventAddress()));
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_OWNER_ID, "" + event.getpEventOwnerId()));
		server_data = new ServerData(Constants.SERVER_URL + url_save_event_info, params);
		String result = server_data.getResultString();
		return_id = Integer.parseInt(result);
		return return_id;
	}
	
	/*
	 * 将'yyyy-mm-dd hh:mm:ss'转换成毫秒数传给php
	 */
	private long dateToMSecond(String date) {
		/*
		 * data = "2012-08-14 10:34:00"
		 */
		int  year = Integer.parseInt(date.substring(0, 4));
		int month = Integer.parseInt(date.substring(5, 7));
		int   day = Integer.parseInt(date.substring(8, 10));
		int  hour = Integer.parseInt(date.substring(11, 13));
		int   min = Integer.parseInt(date.substring(14, 16));
		Timestamp stamp = new Timestamp(year - 1900, month - 1, day, hour, min, 0, 0);
		return stamp.getTime();
	}
	
	/* 发送活动邀请 - pCC02F04
	 * 向选定的好友发送活动邀请，将好友id、活动id、
	 * pTableUserEvent.EVENT_UNCONFIRMED(false)
	 * 组成一条新记录插入用户活动记录表中。
	 * 其中EVENT_UNCONFIRMED将在php中写死
	 * 先把返回值void 改为 String，方便测试
	 */
	public int pSendInvitation(int event_id, List<pTableUserInfo> users) {
		int return_id = 0;
		int users_count = 0;
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_ID, "" + event_id));
		for (Iterator<pTableUserInfo> iterator = users.iterator();iterator.hasNext();) {
			pTableUserInfo user = iterator.next();
			int user_id = user.get_id();
			String key = Constants.PARAM_USER_ID + (users_count++);
			params.add(new BasicNameValuePair(key, "" + user_id));
		}
		// 添加链表的长度，用于在php中处理post传递来的参数
		params.add(new BasicNameValuePair(Constants.PARAM_USERS_COUNT, "" + users_count));
		
		server_data = new ServerData(Constants.SERVER_URL + url_send_invitation, params);
		String result = server_data.getResultString();
		return_id = Integer.parseInt(result);
		return return_id;
		/*if (!result.equals("")) {
			return_id = Integer.parseInt(result);
		}*/
	}
	/* 
	 * 修改活动状态 - pCC02F05
	 * 如修改成功则返回该活动id，否则返回null。活动状态使用活动资料类中的4个static值。
	 * return_id = -1 	操作失败
	 * return_id = 0  	未更新
	 * return_id = n	返回的id
	 */ 
	public int pEventStateChange(int event_id, int event_state) {
		int return_id = -1;
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_ID, "" + event_id));
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_STATE, "" + event_state));
		server_data = new ServerData(Constants.SERVER_URL + url_state_change, params);
		String result = server_data.getResultString();
		return_id = Integer.parseInt(result);
		return return_id;
	}
	
	/*
	 * 获得活动列表数据 - pCC02F06
	 * 对用户活动记录表和活动信息表进行联合查询，
	 * 查询条件除了给定的用户id和活动状态外，
	 * 用户活动记录表中是否已接受邀请字段的值为pTableUserEvent.EVENT_CONFIRMED(true)，
	 * 返回一个活动信息类的实例数组。
	 * 改为 返回一个活动信息类的实例列表，否则与pScrMain_>pShowEventList表述不一致，
	 * 将不能放入ListView中
	 */
	public LinkedList<pTableEventInfo> pGetEventList(int user_id, int event_state) {
		//pTableEventInfo events[] = new pTableEventInfo[6];
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair(Constants.PARAM_USER_ID, "" + user_id));
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_STATE, "" + event_state));
		server_data = new ServerData(Constants.SERVER_URL + url_get_event_list, params);
		LinkedList<pTableEventInfo> list = getEventList(server_data.getResultJsonString());
		/*int size = list.size();
		pTableEventInfo events[] = new pTableEventInfo[size];
		for (int i = 0; i < size; i++) {
			events[i] = list.get(i);
		}*/
		return list;
	} 
	
	/*
	 * 修改活动的邀请状态 - pCC02F07
	 * 将该用户这个活动的邀请状态改成已接受
	 * 参数为什么不是这个邀请的id？
	 * 返回1表示确认
	 * 返回0表示数据库操作并未更新，也就是说本来就是邀请被确认的状态
	 * 返回-1表示数据库操作失败
	 */
	public int pConfirmInvitation(int user_id, int event_id) {
		int return_id = -1;
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair(Constants.PARAM_USER_ID, "" + user_id));
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_ID, "" + event_id));
		server_data = new ServerData(Constants.SERVER_URL + url_confirm_invitation, params);
		String result = server_data.getResultString();
		return_id = Integer.parseInt(result);
		return return_id;
	}
	
	/*
	 * pCC02F08 - 获得未接受邀请的活动列表数据
	 * 根据给定的用户id在用户活动记录表中查询字段是否已接受邀请的值
	 * 为pTableUserEvent.EVENT_UNCONFIRMED(false)的记录，
	 * 返回一个活动信息类的实力数组。
	 * 改为 返回一个活动信息类的实例列表，否则与pScrMain_>pShowEventList表述不一致，
	 * 将不能放入ListView中
	 */
	public LinkedList<pTableEventInfo> pGetEventUnconfirmed(int user_id) {
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair(Constants.PARAM_USER_ID, "" + user_id));
		server_data = new ServerData(Constants.SERVER_URL + url_unconfirmed_event, params);
		String sd_json_data = server_data.getResultJsonString();
		//Log.e("ctrlEventInfo", "json = " + sd_json_data);
		LinkedList<pTableEventInfo> list = this.getEventList(sd_json_data);
		/*int size = list.size();
		pTableEventInfo events[] = new pTableEventInfo[size];
		for (int i = 0; i < size; i++) {
			events[i] = list.get(i);
		}*/
		return list;
	}
	
	public LinkedList<pTableEventInfo> getEventList(String json_str) {
		//getResultJsonString();
		Type listType = new TypeToken<LinkedList<pTableEventInfo>>() {}.getType();
		Gson gson = new Gson();
		//Log.e("pCtrlEventInfo", "json_str = " + json_str);
		LinkedList<pTableEventInfo> events = gson.fromJson(json_str, listType);
		Log.e(TAG, "活动数有" + events.size());
		return events;
	}
	
	public pTableEventInfo getEvent(String json_str) {
		pTableEventInfo event = null;
		Type listType = new TypeToken<LinkedList<pTableEventInfo>>() {}.getType();
		Gson gson = new Gson();
		//Log.e("pCtrlEventInfo", "json_str = " + json_str); 
		LinkedList<pTableEventInfo> events = gson.fromJson(json_str, listType);
		Iterator<pTableEventInfo> iterator = (Iterator<pTableEventInfo>)(events.iterator());
		if (iterator != null) {
			event = (pTableEventInfo)(iterator.next());
		}
		
		/*
		 * 	Type listType = new TypeToken<LinkedList<User>>() {}.getType();
			Gson gson = new Gson();
			LinkedList<User> users = gson.fromJson(jsonData, listType);
			for (Iterator<User> iterator = users.iterator(); iterator.hasNext();) {
				User user = (User) iterator.next();
				int uid = user.getUid();
			}
		 */
		//for (Iterator<pTableEventInfo> iterator = events.iterator(); iterator.hasNext();) {
			//event = (pTableEventInfo) iterator.next();
		//}
		//Iterator<pTableEventInfo> iterator = events.iterator();
		//event = iterator.next();
		return event;
	}
	
	public LinkedList<pTableUserEvent> getUserEventList(String json_str) {
		Type listType = new TypeToken<LinkedList<pTableUserEvent>>() {}.getType();
		Gson gson = new Gson();	
		//Log.e("pCtrlEventInfo", "json_str = " + json_str);
		LinkedList<pTableUserEvent> user_events = gson.fromJson(json_str, listType);
		return user_events;
	}
	
	/*
	 * 新增
	 * 获取一个活动的参与人列表
	 * 可增加的参数，用于表示参与人的状态LinkedList states_list
	 */
	public LinkedList<pTableUserInfo> pGetUserEvents(int event_id) {
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair(Constants.PARAM_EVENT_ID, "" + event_id));
		server_data = new ServerData(Constants.SERVER_URL + url_event_users, params);
		String sd_json_data = server_data.getResultJsonString();
		LinkedList<pTableUserEvent> list = this.getUserEventList(sd_json_data);
		Log.e(TAG, "参与人数有 = " + list.size());
		LinkedList<pTableUserInfo> participants_list = new LinkedList<pTableUserInfo>();
		for (Iterator<pTableUserEvent> it = (Iterator<pTableUserEvent>)(list.iterator()); it.hasNext();) {
			pTableUserInfo participant = new pTableUserInfo();
			pTableUserEvent user_event = it.next();
			participant.set_id(user_event.getpUserId());
			participants_list.add(participant);
			// states_list.add(user_event.getpIfConfirmInvite());
		}
		return participants_list;
	}
	
}
